package com.jml.Lock;


import java.util.concurrent.atomic.AtomicReference;

/**
 * @author:jml
 * @date: 2019/4/29 16:10
 * @description：
 */
public class 自旋锁 {

    //没有set默认里面的Thread为null
    AtomicReference<Thread> atomicReference  = new  AtomicReference<Thread>();

    public static void main(String[] args) {
        自旋锁 zi = new 自旋锁();
        new Thread(()->{
            zi.myLock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            zi.myUnLock();
        },"aa").start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            zi.myLock();
            zi.myUnLock();
        },"bb").start();
    }
    //自旋锁加锁
    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"come in");
        while(!atomicReference.compareAndSet(null,thread)){
        }
    }
    //解锁
    public void myUnLock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"come out");
    }
}
